<template>
  <div style="height: 100%">
    <div class="form-model-box">
      <a-select v-model:value="formModelId" :showSearch="true" placeholder="请选择查询的模型" allowClear style="width: 200px" @change="handleChange">
        <a-select-option v-for="(item, index) in formModelOptions" :value="item.value" :key="index">{{ item.label }}</a-select-option>
      </a-select>
    </div>
    <BeTable
      class="asset-interaction-records"
      rowKey="id"
      :columns="columns"
      :pagination="{ pageSize: pageSize, total: total }"
      :scroll="{ x: '100%' }"
      :formSetting="{ fields: searchFields, showExpandButton: false, maxShowFields: 1000, defultValue: defultValue }"
      :beforeFetch="beforeFetch"
      :api="getAssetInteractionRecordsList"
      ref="tableRef"
    >
      <template #toolbar>
        <BeButton type="primary" @click="showAddFilteringCriteria = true">新增筛选条件</BeButton>
        <BeButton type="primary" @click="handleCreateModal">保存查询模型</BeButton>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'resultFlag'">
          <div class="result-flag">
            <span :class="['dot', record.resultFlag === '成功' ? 'status-success' : record.resultFlag == '失败' ? 'status-fail' : '']"></span>
            <span>{{ record.resultFlag }}</span>
          </div>
        </template>
        <template v-if="column.key === 'resourcePath'">
          <div class="resource-path">{{ record.resourcePath }}</div>
        </template>
        <template v-if="column.key === 'action'">
          <a-button type="link" @click="handleView(record)">查看详情</a-button>
        </template>
      </template>
    </BeTable>
    <AddFilteringCriteria v-model:showModal="showAddFilteringCriteria" @saveSelectedFields="handleSelectedFields" />
    <Create v-model:showModal="showCreateModal" :contents="contents" @reload="getFormModelOptions" />
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { TableColumnsType } from 'ant-design-vue'
import AddFilteringCriteria from './AddFilteringCriteria.vue'
import { logAuditApi } from '@/api/log-audit'
import type { GetlogAuditParams, LogAuditRecords } from '@/api/log-audit/type'
import { definedFields, queryFields } from './data'
import dayjs from 'dayjs'
import Create from './create.vue'
defineOptions({ name: 'LogAuditRecords' })
const emit = defineEmits(['handleListEmit'])
const tableRef = ref()
const pageSize = ref(15)
const total = ref(0)
const showAddFilteringCriteria = ref(false)
const showCreateModal = ref(false)
const searchParams = ref<GetlogAuditParams>({})
//模型查询
const formModelId = ref<string | undefined>(undefined)
const contents = ref<string>('')

const defultValue = ref({})
//模型查询下拉数据
const formModelOptions = ref<any>([])
// 搜索字段
const searchFields = ref<any>(JSON.parse(JSON.stringify(definedFields)))

// 列定义
const columns: TableColumnsType = [
  { title: '涉敏类型', align: 'left', dataIndex: 'what_log_remarksa5', key: '(what_log_remarksa5', width: '10%' },
  { title: '服务端IP', dataIndex: 'whereto_dev_dip_str', key: 'whereto_dev_dip_str', width: '10%' },
  { title: '服务端端口', dataIndex: 'whereto_dev_dport', key: 'whereto_dev_dport', width: '10%' },
  { title: '涉敏个数', dataIndex: 'what_log_remarksa3', key: 'what_log_remarksa3', width: '8%' },
  {
    title: '涉敏内容',

    dataIndex: 'what_op_cont',
    key: 'what_op_cont',
    width: '10%'
  },
  { title: '时间', dataIndex: 'when_op_datetime', key: 'when_op_datetime', width: '10%' },
  { title: '客户端IP', dataIndex: 'wherefrom_dev_sip_str', key: 'wherefrom_dev_sip_str', width: '10%' },
  { title: '授权凭证（UA）', dataIndex: 'why_form_remarks', key: 'why_form_remarks', width: '8%' },
  { title: '域名', dataIndex: 'what_dev_app_domain', key: 'what_dev_app_domain', width: '8%' },
  { title: '资产路径', align: 'left', dataIndex: 'what_dev_app_url', key: 'what_dev_app_url', width: '10%' },
  { title: '操作', align: 'center', key: 'action', width: '120px', fixed: 'right' }
]

// 行选择
const selectedRowKeys = ref<(string | number)[]>([])
const _rowSelection = ref({
  selectedRowKeys,
  onChange: (keys: (string | number)[], _selectedRows: any) => {
    selectedRowKeys.value = keys
  }
})

// // 处理搜索前参数（BeTable 会传入 params）
const beforeFetch = (params: any) => {
  searchParams.value = params
  // 定义字段映射关系
  // 根据当前 searchFields 构造字段映射，便于查找 label/component
  const fieldMapping: { [key: string]: { name: string; column: string; component?: string } } = {}
  for (const f of searchFields.value) {
    if (f && f.prop) {
      fieldMapping[f.prop] = {
        name: f.label,
        column: f.prop,
        component: f.component
      }
    }
  }

  // 构造 conditions 数组
  const conditions = [
    {
      name: '主键',
      column: 'what_op_app_id',
      type: 'string',
      conditionValue: {
        value: 'api_sensitive_log'
      }
    }
  ]
  for (const [key, value] of Object.entries(params)) {
    if (value && fieldMapping[key]) {
      if (fieldMapping[key].component === 'RangePicker' && Array.isArray(value)) {
        conditions.push({
          name: fieldMapping[key].name,
          column: fieldMapping[key].column,
          type: 'datetime',
          conditionValue: {
            beginDateTime: dayjs(value[0]).format('YYYY-MM-DD') + ' 00:00:00',
            endDateTime: dayjs(value[1]).format('YYYY-MM-DD') + ' 23:59:59'
          } as any
        })
      } else {
        conditions.push({
          name: fieldMapping[key].name,
          column: fieldMapping[key].column,
          type: 'string',
          conditionValue: {
            value: Array.isArray(value) ? value.join(',') : value
          } as any
        })
      }
    }
  }
  let obj = {
    pageIndex: params.page + 1,
    pageSize: pageSize.value,
    conditions: conditions,
    sort: {
      field: [],
      type: ''
    },
    columns: [],
    pageSign: ''
  }

  return obj
}

// 获取接口列表
const getAssetInteractionRecordsList = async (params?: GetlogAuditParams) => {
  return logAuditApi.GetLogAuditRecordsList({ data: { ...params } })
}
const handleSelectedFields = (fields: string[]) => {
  searchFields.value = [
    ...JSON.parse(JSON.stringify(definedFields)),
    ...fields.map((field) => {
      return queryFields.find((item) => item.prop === field)
    })
  ]
}
//模型下拉数据
const getFormModelOptions = async () => {
  try {
    const res: any = await logAuditApi.GetLogAuditModelList()
    formModelOptions.value = res.map((item: any) => {
      return {
        ...item,
        label: item.name,
        value: item.id
      }
    })
  } catch (error) {
    console.error('获取模型下拉数据失败：', error)
  }
}
//保存模型
const handleCreateModal = async () => {
  const data = await tableRef.value?.formRefs.formModel
  const definedFieldProps = definedFields.map((field) => field.prop)
  let contentsArr = searchFields.value
    .filter((f: any) => !definedFieldProps.includes(f.prop))
    .map((item: any) => {
      return {
        name: item.label,
        column: item.prop,
        type: 'string',
        conditionValue: {
          value: Array.isArray(data[item.prop]) ? data[item.prop].join(',') : data[item.prop]
        }
      }
    })
  contents.value = JSON.stringify(contentsArr)
  nextTick(() => {
    showCreateModal.value = true
  })
}
const handleChange = async (value: string) => {
  let dataForm: any = {}
  if (value) {
    const find = formModelOptions.value.find((item: any) => item.value === value)
    const contentsArr = JSON.parse(find.contents)
    searchFields.value = [
      ...JSON.parse(JSON.stringify(definedFields)),
      ...contentsArr.map((item: any) => {
        return {
          ...queryFields.find((item2: any) => item2.prop === item.column)
        }
      })
    ]
    contentsArr.forEach((item: any) => {
      const find02: any = queryFields.find((item2: any) => item2.prop === item.column)

      if (find02?.component == 'RangePicker') {
        dataForm[item.column] = item.conditionValue.value ? item.conditionValue.value.split(',') : []
      } else {
        dataForm[item.column] = item.conditionValue.value || ''
      }
    })
  } else {
    searchFields.value = JSON.parse(JSON.stringify(definedFields))
  }
  defultValue.value = dataForm
  const res = await tableRef.value?.formRefs
  res.formModel = JSON.parse(JSON.stringify(dataForm))
  setTimeout(async () => {
    await tableRef.value?.formRefs.reset()
  }, 500)
}
//查看详情
const handleView = async (record: any) => {
  emit('handleListEmit', record)
}
onMounted(() => {
  getFormModelOptions()
})
</script>

<style lang="scss" scoped>
.form-model-box {
  padding: 0px 12px;
  margin-top: 12px;
  display: flex;
  justify-content: end;
}
.asset-interaction-records {
  height: calc(100% - 40px) !important;
  // padding: 0 20px;
  // background-color: var(--color-white);
  .result-flag {
    .dot {
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background-color: #b1b1b3;
      display: inline-block;
      margin-right: 5px;
    }
    .status-success {
      background-color: var(--success);
    }
    .status-fail {
      background-color: var(--error);
    }
  }
  .resource-path {
    color: var(--primary);
  }
}
</style>
